<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-calendar"></i>
                    <router-link to="/contract">合同管理</router-link>
                </el-breadcrumb-item>
                <el-breadcrumb-item>合同附件</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <span>当前合同 {{ contract.contractName }}</span>
            </div>
            <div class="file-box">
                <el-upload
                    class="upload-demo"
                    ref="upload"
                    action="#"
                    :accept="upload.accept"
                    :http-request="handleUploadFile"
                    :before-upload="beforeFileUpload"
                    :on-change="handleChange"
                    :file-list="fileList"
                    :auto-upload="false"
                    :show-file-list="true"
                >
                    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                    <div class="el-upload el-upload--text el-upload--submit">
                        <el-button style="margin-left: 10px" size="small" type="success" @click="submitUpload">上传文件</el-button>
                    </div>
                    <div slot="tip" class="el-upload__tip">支持上传图片、pdf、txt、word、excel、ppt,限制文件大小10MB</div>
                </el-upload>
            </div>
            <div class="handle-box">
                <el-input
                    v-model="query.keyword"
                    placeholder="请输入附件名、路径或md5值"
                    class="handle-input mr10"
                    @keyup.native.enter="handleSearch"
                ></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
                <el-table-column prop="attachId" label="ID" width="100" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="attachName" label="附件名称"></el-table-column>
                <el-table-column prop="md5" label="文件MD5"></el-table-column>
                <el-table-column prop="attachType" label="附件类型"></el-table-column>
                <el-table-column prop="sizeString" label="附件大小"></el-table-column>
                <el-table-column prop="uploadTime" label="上传时间"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-view" @click="handleViewFile(scope.$index, scope.row)">查看</el-button>
                        <el-button type="text" icon="el-icon-download" @click="handleDownloadFile(scope.$index, scope.row)">下载</el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page.sync="pageParams.currentPage"
                    :page-size.sync="pageParams.pageSize"
                    :page-count="pageParams.totalElements"
                    :total="pageParams.totalElements"
                    @current-change="getContractData"
                ></el-pagination>
            </div>
        </div>

        <el-dialog
            title="上传进度"
            :visible.sync="upload.dialog"
            append-to-body
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :show-close="false"
        >
            <el-progress :percentage="upload.progress"></el-progress>
            <p style="text-align: center; margin: 10px 0">已上传大小：{{ upload.loaded }}，总大小： {{ upload.total }}</p>
        </el-dialog>
    </div>
</template>

<script>
//import { fetchData } from '../../api/index';
import { dateToString, getFromDateAndTime } from '../../util/DateUtil.js';
import { Base64 } from 'js-base64';
import * as api from '@/api/index.js';
export default {
    name: 'contractAttachment',
    data() {
        return {
            query: {
                keyword: ''
            },
            upload: {
                accept: '.png,.jpg,.jpeg,.bmp,.pdf,.txt,.docx,.doc,.xls,.xlsx,.ppt,.pptx',
                progress: 0,
                loaded: 0,
                total: 0,
                dialog: false
            },
            pageParams: {
                currentPage: 1,
                pageSize: 10,
                totalElements: 20,
                totalPages: 1
            },
            contract: [],
            file: {},
            fileList: [],
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 4,
            form: {},
            idx: -1,
            id: -1
        };
    },
    created() {
        this.getData();
    },
    watch: {
        $route(to, from) {
            if (this.$route.params.contractId) {
                this.getData();
            }
        }
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    let attachId = row.attachId;
                    let contractId = this.$route.params.contractId;
                    api.delAttachmentByContractidAndAttachId(contractId, attachId)
                        .then((res) => {
                            if (res.code === 200) {
                                this.$message.success('删除成功');
                                this.getData();
                            } else {
                                this.$message.error('删除失败');
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                })
                .catch(() => {});
        },
        handleViewFile(index, row) {
            let contractId = this.$route.params.contractId;
            let attachId = row.attachId;
            let url = api.getAttachmentViewURL(contractId, attachId, row.attachName);
            window.open(url);
        },
        handleDownloadFile(index, row) {
            let contractId = this.$route.params.contractId;
            let attachId = row.attachId;
            let url = api.getAttachmentDownloadURL(contractId, attachId, row.attachName);
            window.open(url);
        },
        handleUploadFile() {
            const files = this.$refs.upload.uploadFiles;
            if (!files || files.length !== 1) {
                this.$message.info('请选择需要上传的文件');
                return;
            }
            let file = files[files.length - 1];
            let params = new FormData();
            params.append('file', file.raw, file.name);
            let contractId = this.$route.params.contractId;
            let progessEvent = (pe) => {
                this.upload.progress = Number.parseInt((pe.loaded / pe.total) * 100);
                this.upload.loaded = pe.loaded;
                this.upload.total = pe.total;
            };

            this.upload.dialog = true;
            this.progress = this.loaded = this.total = 0;
            api.saveAttachmentByContractId(contractId, params, progessEvent)
                .then((res) => {
                    console.log(res);
                    if (res.code === 200) {
                        this.$message.success(res.msg);
                        this.$refs.upload.clearFiles();
                        this.getData();
                    } else {
                        this.$message.success(res.msg);
                    }
                    this.upload.dialog = false;
                })
                .catch((err) => {
                    console.log(err);
                    this.upload.dialog = false;
                });
        },
        submitUpload() {
            const files = this.$refs.upload.uploadFiles;
            if (!files || files.length !== 1) {
                this.$message.info('请选择需要上传的文件');
                return;
            }
            this.$refs.upload.submit();
        },
        beforeFileUpload(file) {
            //let type = file.name.substring(file.name.lastIndexOf('.') + 1, file.name.length);
            let isOverLimitSize = file.size / 1024 / 1024 < 10;
            if (!isOverLimitSize) {
                this.$message.error('上传文件大小不能超过 10MB');
            }
            return isOverLimitSize;
        },
        handleChange(file, fileList) {
            console.log(fileList.length);
            if (fileList.length > 0) {
                this.fileList = [fileList[fileList.length - 1]];
            }
        },
        getData() {
            this.getContractData();
            this.getAttachmentData();
        },
        getAttachmentData() {
            let contractId = this.$route.params.contractId;
            let currentPage = this.pageParams.currentPage;
            let pageSize = this.pageParams.pageSize;
            let data = this.query;
            api.getAttachmentPageByContractId(contractId, currentPage, pageSize, data)
                .then((res) => {
                    //console.log(res);
                    if (res.code === 200) {
                        this.tableData = res.data.content;
                        this.pageParams.currentPage = res.data.currentPage;
                        this.pageParams.pageSize = res.data.pageSize;
                        this.pageParams.totalElements = res.data.totalElements;
                        this.pageParams.totalPages = res.data.totalPages;
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        getContractData() {
            let contractId = this.$route.params.contractId;
            api.getContractById(contractId)
                .then((res) => {
                    if (res.code === 200) {
                        this.contract = res.data;
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 触发搜索按钮
        handleSearch() {
            this.getData();
        }
    }
};
</script>

<style scoped>
/* 处理上传动画效果 */
.upload-demo >>> .el-list-enter-active,
.upload-demo >>> .el-list-leave-active {
    transition: none;
}
.upload-demo >>> .el-list-enter,
.upload-demo >>> .el-list-leave-active {
    opacity: 0;
}
.upload-demo >>> .el-upload-list {
    height: 40px;
}
.upload-demo >>> .el-upload {
    width: 80px;
    height: 32px;
    border: none;
    text-align: center;
}
.upload-demo >>> .el-upload--submit {
    width: 100px;
    height: 32px;
    border: none;
    text-align: center;
}
.file-box {
    margin-bottom: 20px;
    width: 360px;
}
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
